﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenericLibrary.ExtensionMethods {

    public static class DictionaryExtension {

        class DictionaryWrapper<TKey, TValue> {

            IDictionary<TKey, TValue> _dictionary;
            List<TKey> _keysToRemove;
            private static DictionaryWrapper<TKey, TValue> _instance = new DictionaryWrapper<TKey, TValue>();

            public static DictionaryWrapper<TKey, TValue> Instance {
                get {
                    return _instance;
                }
            }

            public void PendingRemove(IDictionary<TKey, TValue> dictionary, TKey key) {
                if(dictionary != this._dictionary) {
                    if(this._keysToRemove.Count > 0) {
                        throw new Exception();
                    }
                    this._dictionary = dictionary;
                }
                this._keysToRemove.Add(key);
            }

            public void CommitRemove(IDictionary<TKey, TValue> dictionary) {
                if(dictionary != this._dictionary) {
                    throw new Exception();
                }

                for(int i = 0; i < this._keysToRemove.Count; i++) {
                    this._dictionary.Remove(this._keysToRemove[i]);
                }

                this._keysToRemove.Clear();
                this._dictionary = null;
            }

            private DictionaryWrapper() {
                this._keysToRemove = new List<TKey>();
            }
        }

        public static void PendingRemove<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key) {
            DictionaryWrapper<TKey, TValue>.Instance.PendingRemove(dictionary, key);
        }

        public static void CommitRemove<TKey, TValue>(this IDictionary<TKey, TValue> dictionary) {
            DictionaryWrapper<TKey, TValue>.Instance.CommitRemove(dictionary);
        }
    }
}
